import React from 'react';
import { Card,Row ,Col ,Modal, Divider, Button, Form, Tree , Select, Spin,Input, Icon, message ,Pagination} from 'antd';
import Utils from './../../../utils/utils';
import './../../../style/style.css';
import './index.less';
import Axios from "../../../axios";
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const TreeNode = Tree.TreeNode;
const Option = Select.Option;

//组织架构第一版  备份
/*export default class OrganDepart extends React.Component {
    state={
        treeDeptData:[],
        allUserData:[],
        createDeptModal:{
            visible: false,
            confirmLoading: false,
        },
        editDeptModal:{
            visible: false,
            confirmLoading: false,
        },
        delDeptModal:{
            visible: false,
            confirmLoading: false,
        },
        addUserModal:{
            visible: false,
            confirmLoading: false,
        },
    }
    componentWillMount(){
        this.treeDeptRequest();     //查询所有部门【级联数据】
        this.allUserRequest();      //查询所有用户
    }
    //选中操作
    handleOnSelect = (selectedKeys, info) => {
        console.log(selectedKeys);
        //console.log(info.node.props);
        if (selectedKeys.length){
            this.setState({
                selectedItem:info.node.props
            })
            let params = {
                deptId:selectedKeys[0]
            }
            this.deptUserRequest(params);
        }else {
            this.setState({
                selectedItem:null
            })
        }
    }
    //对节点操作
    handleNode = (type)=>{
        let isSelected = this.state.selectedItem;
        /!*if (type=="delDept"){

        }*!/
        if(type=="addDept"){
            this.setState({
                createDeptModal:{
                    ...this.state.createDeptModal,
                    visible:true
                }
            })
        }else if(type=="editDept"){
            this.setState({
                editDeptModal:{
                    ...this.state.editDeptModal,
                    visible:true
                }
            })
        }else if(type=="delDept"){
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    visible:true
                }
            })
        }else if(type=="addUser"){
            this.setState({
                addUserModal:{
                    ...this.state.addUserModal,
                    visible:true
                }
            })
        }
    }
    //添加下级部门 确定
    handleCreateDeptSubmit = ()=>{
        const _form = this.createDeptForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values)
            let params = Utils.FilterParam(values); //过滤掉为空的参数
            this.addDeptRequest(params);
            // _form.resetFields();//清空表单
        });
    }
    //编辑部门 确定
    handleEditDeptSubmit = ()=>{
        const _form = this.editDeptForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values)
            let params = Utils.FilterParam(values); //过滤掉为空的参数
            this.editDeptRequest(params);
            // _form.resetFields();//清空表单
        });
    }
    //删除部门确定
    handleDelDeptSubmit = ()=>{
        const _form = this.delDeptForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values)
            let params = Utils.FilterParam(values); //过滤掉为空的参数
            this.delDeptRequest(params)
            // _form.resetFields();//清空表单
        });
    }
    //部门添加用户确定
    handleAddUserSubmit = ()=>{
        const _form = this.addUserForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values)
            let params = Utils.FilterParam(values); //过滤掉为空的参数
            this.addUserRequest(params)
            // _form.resetFields();//清空表单
        });
    }
    //移除部门用户
    handleDelUser = (id)=>{
        let deptId = this.state.selectedItem.dataRef.id
        console.log(id)
        let params = {
            deptId,
            userId:id
        }
        Modal.confirm({
            title: '确认删除？',
            content: '删除后数据不可恢复！',
            okText: '确认',
            cancelText: '取消',
            onOk:()=>{
                this.delUserRequest(params);
            }
        });
    }
    //查询所有部门【级联数据】
    treeDeptRequest = ()=>{
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.dataRequest({
            block:'/hr',
            url:'/department/cascade',
            params:'',
        }).then((data)=>{
            console.log(data)
            let treeDeptData = data.data;
            this.setState({
                loading:false,
                treeDeptData,
                //selectedItem:null
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    //查询所有简单用户信息
    allUserRequest = ()=>{
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.dataRequest({
            block:'/hr',
            url:'/user/allUserSmallInfos',
            params:'',
        }).then((data)=>{
            console.log(data)
            let allUserData = data.data;
            this.setState({
                loading:false,
                allUserData
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    //添加下级部门请求
    addDeptRequest = (params)=>{
        this.setState({
            createDeptModal:{
                ...this.state.createDeptModal,
                confirmLoading: true,
            }
        })
        Axios.formRequest({
            block:'/hr',
            url:'/department',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                createDeptModal:{
                    ...this.state.createDeptModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('添加成功！',2,()=>{
                    //window.location.reload();
                    this.treeDeptRequest();
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                createDeptModal:{
                    ...this.state.createDeptModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //编辑部门请求
    editDeptRequest = (params)=>{
        this.setState({
            editDeptModal:{
                ...this.state.editDeptModal,
                confirmLoading: true,
            }
        })
        Axios.formPutRequest({
            block:'/hr',
            url:'/department',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                editDeptModal:{
                    ...this.state.editDeptModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('修改成功！',2,()=>{
                    window.location.reload();
                    //this.treeDeptRequest();
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                editDeptModal:{
                    ...this.state.editDeptModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //删除部门请求
    delDeptRequest = (params)=>{
        this.setState({
            delDeptModal:{
                ...this.state.delDeptModal,
                confirmLoading: true,
            }
        })
        Axios.delRequest({
            block:'/hr',
            url:'/department',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('删除成功！',2,()=>{
                    //window.location.reload();
                    this.treeDeptRequest();
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //部门添加用户请求
    addUserRequest = (params)=>{
        this.setState({
            addUserModal:{
                ...this.state.addUserModal,
                confirmLoading: true,
            }
        })
        Axios.formRequest({
            block:'/hr',
            url:'/department/member',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                addUserModal:{
                    ...this.state.addUserModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('添加成功！',2,()=>{
                    //window.location.reload();
                    let _params = {
                        deptId:params.deptId
                    }
                    this.deptUserRequest(_params);
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                addUserModal:{
                    ...this.state.addUserModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //查询部门用户列表
    deptUserRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.dataRequest({
            block:'/hr',
            url:'/user/queryByDept',
            params:params,
        }).then((data)=>{
            console.log(data)
            let deptUserData = data.data;
            this.setState({
                loading:false,
                deptUserData,
                //selectedItem:null
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    //删除部门某个用户请求
    delUserRequest = (params)=>{
        this.setState({
            delDeptModal:{
                ...this.state.delDeptModal,
                confirmLoading: true,
            }
        })
        Axios.delRequest({
            block:'/hr',
            url:'/department/member',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('删除成功！',2,()=>{
                    let _params = {
                        deptId:params.deptId
                    }
                    this.deptUserRequest(_params);
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //部门树节点渲染
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.childs) {
                return (
                    <TreeNode title={item.name} key={item.id} dataRef={item}>
                        {this.renderTreeNodes(item.childs)}
                    </TreeNode>
                );
            }
            return <TreeNode title={item.name} key={item.id} dataRef={item} />;
        });
    }
    render(){
        const deptUserData = this.state.deptUserData || [];
        return(
            <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                <div className="organize-box">
                    <Card title="组织部门管理">
                        <Row>
                            <Col sm={12} style={{paddingRight:30}}>
                                <div className="op-box">
                                    <div style={{marginRight:30}}>{this.state.selectedItem?<div>当前选中部门 <span className="txt-primary" style={{fontWeight:"bold"}}>{this.state.selectedItem.title}</span></div>:<div>当前未选中任何节点</div>}</div>
                                    {this.state.selectedItem?
                                        <div>
                                            <a className="btn-txt-primary" onClick={()=>this.handleNode("addDept")}>添加下级部门</a>
                                            <Divider type="vertical" />
                                            <a className="btn-txt-primary" onClick={()=>this.handleNode("addUser")}>添加部门成员</a>
                                            {this.state.selectedItem.dataRef.parentId
                                                ?
                                                <span>
                                                    <Divider type="vertical" />
                                                    <a className="btn-txt-primary" onClick={()=>this.handleNode("editDept")}>编辑部门</a>
                                                    <Divider type="vertical" />
                                                    <a className="btn-txt-danger" onClick={()=>this.handleNode("delDept")}>删除部门</a>
                                                </span>
                                                :''
                                            }
                                        </div>
                                        :''}
                                </div>
                                <Tree
                                    onSelect={this.handleOnSelect}
                                >
                                    {this.renderTreeNodes(this.state.treeDeptData)}
                                </Tree>
                            </Col>
                            <Col sm={12}>
                                <div style={{textAlign:'center',marginBottom:15,}}>{this.state.selectedItem?<div><span className="txt-primary" style={{fontWeight:"bold"}}>{this.state.selectedItem.title}</span>成员</div>:''}</div>
                                <div>
                                    {
                                        deptUserData.length
                                            ?
                                            deptUserData.map((item)=>{
                                                return  <span className="user-list" key={item.id}>{item.name}<Icon type="close" onClick={()=>this.handleDelUser(item.id)} className="btn-close"/></span>
                                            })
                                            :
                                            <div>
                                                {this.state.selectedItem?<div style={{textAlign:'center'}}>该部门暂无用户</div>:''}
                                            </div>
                                    }

                                </div>
                            </Col>
                        </Row>
                    </Card>
                    <Modal title="添加下级部门"
                           visible={this.state.createDeptModal.visible}
                           onOk={this.handleCreateDeptSubmit}
                           okText="确认添加"
                           confirmLoading={this.state.createDeptModal.confirmLoading}
                           destroyOnClose={true}
                           onCancel={()=>{
                               this.setState({
                                   createDeptModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <CreateDeptForm allUserData={this.state.allUserData} selectedItem={this.state.selectedItem} wrappedComponentRef={(createDeptForm)=>{this.createDeptForm = createDeptForm;}}/>
                    </Modal>
                    <Modal title="编辑部门"
                           visible={this.state.editDeptModal.visible}
                           onOk={this.handleEditDeptSubmit}
                           okText="确认修改"
                           confirmLoading={this.state.editDeptModal.confirmLoading}
                           destroyOnClose={true}
                           onCancel={()=>{
                               this.setState({
                                   editDeptModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <EditDeptForm allUserData={this.state.allUserData} selectedItem={this.state.selectedItem} wrappedComponentRef={(editDeptForm)=>{this.editDeptForm = editDeptForm;}}/>
                    </Modal>
                    <Modal title="删除部门"
                           visible={this.state.delDeptModal.visible}
                           onOk={this.handleDelDeptSubmit}
                           okText="确认删除"
                           confirmLoading={this.state.delDeptModal.confirmLoading}
                           destroyOnClose={true}
                           onCancel={()=>{
                               this.setState({
                                   delDeptModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <DelDeptForm selectedItem={this.state.selectedItem} wrappedComponentRef={(delDeptForm)=>{this.delDeptForm = delDeptForm;}}/>
                    </Modal>
                    <Modal title="添加部门成员"
                           visible={this.state.addUserModal.visible}
                           onOk={this.handleAddUserSubmit}
                           okText="确认添加"
                           confirmLoading={this.state.addUserModal.confirmLoading}
                           destroyOnClose={true}
                           onCancel={()=>{
                               this.setState({
                                   addUserModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <AddUserForm allUserData={this.state.allUserData} selectedItem={this.state.selectedItem} wrappedComponentRef={(addUserForm)=>{this.addUserForm = addUserForm;}}/>
                    </Modal>
                </div>
            </Spin>
        )
    }
}*/

//创建部门
class CreateDeptForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const levelArr = [1,2,3,4,5,6,7,8,9]
        const lvOptions = levelArr.map((item)=>{
            return <Option key={item} value={item}>{item}</Option>
        })
        const allUserData = this.props.allUserData || [];
        const ldOptions = allUserData.map((item)=>{
            return <Option key={item.id} value={item.id}>{item.name}</Option>
        })
        const selectedItem = this.props.selectedItem;
        const parentId = selectedItem.dataRef.id;
        return (
            <Form>
                <FormItem {...formItemLayout} style={{display:'none'}}>
                    {
                        getFieldDecorator('parentId',{//父级部门编号
                            initialValue:parentId
                        })(
                            <Input type="hidden" placeholder=""/>
                        )
                    }
                </FormItem>
                <FormItem label="部门名称" {...formItemLayout}>
                    {
                        getFieldDecorator('name',{
                            rules: [{ required: true, message: '请输入部门名称!' }],
                        })(
                            <Input type="text" placeholder="部门名称"/>
                        )
                    }
                </FormItem>
                <FormItem label="部门leader" {...formItemLayout}>
                    {
                        getFieldDecorator('leaderUserId', {
                            rules: [{ required: true, message: '请选择部门leader!' }],
                        })(
                            <Select placeholder="部门leader">
                                {ldOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="部门级别" {...formItemLayout}>
                    {
                        getFieldDecorator('level', {
                            rules: [{ required: true, message: '请选择部门级别!' }],
                        })(
                            <Select placeholder="部门级别">
                                {lvOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="部门描述" {...formItemLayout}>
                    {
                        getFieldDecorator('description',{
                        })(
                            <TextArea placeholder="部门描述" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
CreateDeptForm = Form.create({})(CreateDeptForm);
//更新部门
class EditDeptForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const levelArr = [1,2,3,4,5,6,7,8,9]
        const lvOptions = levelArr.map((item)=>{
            return <Option key={item} value={item}>{item}</Option>
        })
        const allUserData = this.props.allUserData || [];
        const ldOptions = allUserData.map((item)=>{
            return <Option key={item.id} value={item.id}>{item.name}</Option>
        })
        const selectedItem = this.props.selectedItem;
        const id = selectedItem.dataRef.id;
        const name = selectedItem.dataRef.name;
        const leaderId = selectedItem.dataRef.leaderId;
        const level = selectedItem.dataRef.level;
        const description = selectedItem.dataRef.description;
        return (
            <Form>
                <FormItem {...formItemLayout} style={{display:'none'}}>
                    {
                        getFieldDecorator('id',{//当前部门编号
                            initialValue:id
                        })(
                            <Input type="hidden" placeholder=""/>
                        )
                    }
                </FormItem>
                <FormItem label="部门名称" {...formItemLayout}>
                    {
                        getFieldDecorator('name',{
                            rules: [{ required: true, message: '请输入部门名称!' }],
                            initialValue:name
                        })(
                            <Input type="text" placeholder="部门名称"/>
                        )
                    }
                </FormItem>
                <FormItem label="部门leader" {...formItemLayout}>
                    {
                        getFieldDecorator('leaderUserId', {
                            rules: [{ required: true, message: '请选择部门leader!' }],
                            initialValue:leaderId
                        })(
                            <Select placeholder="部门leader">
                                {ldOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="部门级别" {...formItemLayout}>
                    {
                        getFieldDecorator('level', {
                            rules: [{ required: true, message: '请选择部门级别!' }],
                            initialValue:level
                        })(
                            <Select placeholder="部门级别">
                                {lvOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="部门描述" {...formItemLayout}>
                    {
                        getFieldDecorator('description',{
                            initialValue:description
                        })(
                            <TextArea placeholder="部门描述" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
EditDeptForm = Form.create({})(EditDeptForm);
//删除部门
class DelDeptForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const selectedItem = this.props.selectedItem;
        const id = selectedItem.dataRef.id;
        const name = selectedItem.dataRef.name;
        return (
            <Form>
                <div className="txt-danger" style={{textAlign:'center',marginBottom:15}}>确认删除部门{name}?删除后数据不可恢复！</div>
                <FormItem {...formItemLayout} style={{display:'none'}}>
                    {
                        getFieldDecorator('id',{//当前部门编号
                            initialValue:id
                        })(
                            <Input type="hidden" placeholder=""/>
                        )
                    }
                </FormItem>
                <FormItem label="备注信息" {...formItemLayout}>
                    {
                        getFieldDecorator('remark',{
                        })(
                            <TextArea placeholder="备注信息" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
DelDeptForm = Form.create({})(DelDeptForm);
//添加部门成员
class AddUserForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const allUserData = this.props.allUserData || [];
        const userOptions = allUserData.map((item)=>{
            return <Option key={item.id} value={item.id}>{item.name}</Option>
        })
        const selectedItem = this.props.selectedItem;
        const deptId = selectedItem.dataRef.id;
        const name = selectedItem.dataRef.name;
        return (
            <Form>
                <div className="txt-danger" style={{textAlign:'center',marginBottom:15,fontSize:18}}>{name}添加用户</div>
                <FormItem {...formItemLayout} style={{display:'none'}}>
                    {
                        getFieldDecorator('deptId',{//当前部门编号
                            initialValue:deptId
                        })(
                            <Input type="hidden" placeholder=""/>
                        )
                    }
                </FormItem>
                <FormItem label="用户名称" {...formItemLayout}>
                    {
                        getFieldDecorator('userId', {
                            rules: [{ required: true, message: '请选择用户!' }],
                        })(
                            <Select placeholder="用户名称">
                                {userOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="备注信息" {...formItemLayout}>
                    {
                        getFieldDecorator('remark',{
                        })(
                            <TextArea placeholder="备注信息" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
AddUserForm = Form.create({})(AddUserForm);